//
//  CouponAlertView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/1.
//

import UIKit

enum CouponAlertViewType{
    case normalAlert
    case inputAlert
}

typealias CouponAlertViewClickBlock = (NSInteger, String) -> Void

class CouponAlertView: UIView {
    var alertType: CouponAlertViewType = .normalAlert
    
    var clickButtonBlock: CouponAlertViewClickBlock?
    
    var loadingBtn: LoaddingButton!
    
    var titleLab: UILabel! = {
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        titleLab.numberOfLines = 1
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        return titleLab
    }()
    
    ///警告
    var inputWarnLab: UILabel = {
        let titleLab = UILabel()
        titleLab.textColor = Theme.redColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 11)
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .left
        return titleLab
    }()
    
    var msgLabel: UILabel = {
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        return titleLab
    }()
    
    var detailLab: UILabel = {
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        return titleLab
    }()
    
    ///标签
    var signLab: UILabel = {
        let titleLab = UILabel()
        titleLab.textColor = Theme.titleLabColor
        titleLab.backgroundColor = UIColor.clear
        titleLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 11)
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byTruncatingTail
        titleLab.textAlignment = .center
        titleLab.layer.borderWidth = 1
        titleLab.layer.cornerRadius = 11
        titleLab.layer.masksToBounds = true
        titleLab.layer.borderColor = Theme.titleLabColor.cgColor
        return titleLab
    }()
    
    var inputTF: UITextField! = {
        let tempTF = UITextField()
        tempTF.textColor = Theme.titleLabColor
        tempTF.font = UIFont.init(name: Theme.PingFangSCRegular, size: 11)
        tempTF.backgroundColor = UIColor.init(hex: 0xF6F9FC)
        tempTF.returnKeyType = .done
        tempTF.keyboardType = .default
        
        let leftView = UIView(frame: CGRect.init(x: 0, y: 0, width: 20, height: 44))
        leftView.backgroundColor = UIColor.init(hex: 0xF6F9FC)
        
        let xingLab = UILabel()
        xingLab.backgroundColor = .white
        xingLab.text = "*"
        xingLab.frame = CGRect.init(x: 0, y: 0, width: 12, height: 44)
        xingLab.textColor = Theme.redColor
        xingLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        xingLab.textAlignment = .left
        leftView.addSubview(xingLab)
        
        tempTF.leftView = leftView
        tempTF.leftViewMode = .always
        return tempTF
    }()
    
    var placeHolder: String? {
        didSet {
            self.inputTF.setExtPlaceHolder(placeHolder: placeHolder ?? "", aColor: Theme.placeholderColor, font: UIFont.init(name: Theme.PingFangSCRegular, size: 11)!)
        }
    }
    
    private var bkgBtnView: UIButton = {
        let tempBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        tempBtn.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
        return tempBtn
    }()
    
    private var contentView: UIView = {
        let tempView = UIView()
        tempView.backgroundColor = UIColor.white
        tempView.layer.cornerRadius = 10
        tempView.layer.masksToBounds = true
        return tempView
    }()
    
    var closeBtn: UIButton = {
        let tempBtn = UIButton()
        tempBtn.setup_image(image: UIImage.init(named: "login_close"))
        return tempBtn
    }()
    
    var cancelBtnTitle: String?
    var otherButtonTitles: [String] = []
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //bkgBtnView.addTarget(self, action: #selector(dismissAlertView), for: .touchUpInside)
        addSubview(bkgBtnView)
        bkgBtnView.addSubview(contentView)
        contentView.addSubview(titleLab)
        contentView.addSubview(msgLabel)
        contentView.addSubview(detailLab)
        contentView.addSubview(signLab)
        contentView.addSubview(closeBtn)
        contentView.addSubview(inputWarnLab)

        inputTF.delegate = self
        contentView.addSubview(inputTF)
        
        closeBtn.isHidden = true
        closeBtn.addTarget(self, action: #selector(self.dismissAlertView), for: .touchUpInside)
    }
    
    public convenience init(title: String, message:String? = nil, detail: String? = nil, signText: String? = nil, cancelButtonTitle: String?, otherButtonTitles: [String]? = []){
        self.init()
        self.titleLab.text = title
        self.msgLabel.text = message
        self.detailLab.text = detail ?? ""
        self.signLab.text = signText ?? ""
        self.cancelBtnTitle = cancelButtonTitle
        self.otherButtonTitles = otherButtonTitles ?? []
    }
    
    func refreashSnapKitLayout(){
        self.addSnpLayout()
        
        
        let _cancel = self.cancelBtnTitle ?? ""
        let _others = self.otherButtonTitles.count
        if (_cancel != "" && _others == 0) ||
            (_cancel == "" && _others == 1) {
            //说明alertView只有一个按钮
            loadingBtn = LoaddingButton()
            loadingBtn.setup_titleLabel(text: self.cancelBtnTitle ?? "")
            loadingBtn.backgroundColor = Theme.mainColor
            loadingBtn.setup_titleColor(color: Theme.whiteColor)
            loadingBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
            loadingBtn.layer.cornerRadius = 4
            loadingBtn.layer.masksToBounds = true
            loadingBtn.addTargetUsingBlock {[weak self] _ in
                self?.bottomBtnAction()
            }
            self.contentView.addSubview(loadingBtn)
            
            loadingBtn.snp.makeConstraints { make in
//                make.centerX.equalTo(contentView.snp.centerX)
                make.height.equalTo(44)
//                make.width.equalTo(contentView.snp.width).dividedBy(1.2)
                make.left.equalTo(25)
                make.right.equalTo(-25)
                make.bottom.equalTo(-30)
                make.top.equalTo(signLab.snp.bottom).offset(30)
            }
        }else if _others == 1 && _cancel != "" {
            //有两个按钮
            let btn1 = LoaddingButton()
            btn1.setup_titleLabel(text: self.cancelBtnTitle ?? "")
            btn1.setBackgroundImage(UIImage.init(color: Theme.whiteColor), for: .normal)
            btn1.setBackgroundImage(UIImage.init(color: Theme.eColor), for: .highlighted)
            btn1.setup_titleColor(color: Theme.titleLabColor)
            btn1.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
            btn1.addTargetUsingBlock {[weak self] _ in
                self?.inputTF.resignFirstResponder()
                self?.clickButtonBlock?(0, self?.inputTF.text ?? "")
                self?.dismissAlertView()
            }
            self.contentView.addSubview(btn1)
            
            let btn2 = UIButton()
            btn2.setup_titleLabel(text: self.otherButtonTitles[0])
            btn2.setBackgroundImage(UIImage.init(color: Theme.whiteColor), for: .normal)
            btn2.setBackgroundImage(UIImage.init(color: Theme.eColor), for: .highlighted)
            btn2.setup_titleColor(color: Theme.mainColor)
            btn2.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
            btn2.addTargetUsingBlock {[weak self] _ in
                self?.inputTF.resignFirstResponder()
                self?.clickButtonBlock?(1, self?.inputTF.text ?? "")
                self?.dismissAlertView()
            }
            self.contentView.addSubview(btn2)
            
            ///横线
            let lineView = UIView()
            lineView.backgroundColor = Theme.lineColor
            self.contentView.addSubview(lineView)
            
            //竖线
            let lineView1 = UIView()
            lineView1.backgroundColor = Theme.lineColor
            self.contentView.addSubview(lineView1)
            
            if self.alertType == .inputAlert {
                lineView.snp.makeConstraints { make in
                    make.left.equalTo(0)
                    make.right.equalTo(0)
                    make.top.equalTo(inputTF.snp.bottom).offset(18)
                    make.height.equalTo(0.5)
                }
            }else{
                lineView.snp.makeConstraints { make in
                    make.left.equalTo(0)
                    make.right.equalTo(0)
                    make.top.equalTo(signLab.snp.bottom).offset(18)
                    make.height.equalTo(0.5)
                }
            }
            
            
            btn1.snp.makeConstraints { make in
                make.height.equalTo(49)
                make.left.equalTo(0)
                make.bottom.equalTo(0)
                make.width.equalTo(contentView.snp.width).dividedBy(2)
                make.top.equalTo(lineView.snp.bottom)
            }
            
            btn2.snp.makeConstraints { make in
                make.height.equalTo(49)
                make.left.equalTo(btn1.snp.right)
                make.right.equalTo(0)
                make.bottom.equalTo(0)
                make.top.equalTo(lineView.snp.bottom)
            }
            
            lineView1.snp.makeConstraints { make in
                make.left.equalTo(btn1.snp.right)
                make.top.equalTo(lineView.snp.bottom)
                make.width.equalTo(0.5)
                make.bottom.equalTo(0)
            }
        }
    }
    
    private func addSnpLayout(){
        bkgBtnView.snp.makeConstraints { make in
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.height.equalTo(kScreenHeight)
        }
        
        self.contentView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-50)
            make.width.greaterThanOrEqualTo(kScreenWidth - 90)
            make.height.greaterThanOrEqualTo(100)
        }
        
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(18)
        }
        
        msgLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(titleLab.snp.bottom).offset(12)
        }
        
        var temp_detail_height: CGFloat = 0
        if detailLab.text !=  "" {
            temp_detail_height = 20
        }
        detailLab.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(msgLabel.snp.bottom).offset(12)
            make.right.equalTo(-12)
            make.height.greaterThanOrEqualTo(temp_detail_height)
        }
            
        var input_height: CGFloat = 0
        if self.alertType == .inputAlert {
            inputTF.isHidden = false
            input_height = 44
        }else{
            inputTF.isHidden = true
        }
        inputTF.snp.makeConstraints { make in
            make.left.equalTo(50)
            make.right.equalTo(-50)
            make.top.equalTo(detailLab.snp.bottom).offset(12)
            make.height.equalTo(input_height)
        }
        
        if self.alertType == .inputAlert {
            self.inputWarnLab.snp.makeConstraints { make in
                make.left.equalTo(inputTF.snp.left)
                make.top.equalTo(inputTF.snp.bottom)
                make.right.equalTo(-50)
                make.height.greaterThanOrEqualTo(22)
            }
        }
        
        var sign_width: CGFloat = 0
        var sign_height: CGFloat = 0
        if self.signLab.text != "" {
            self.signLab.sizeToFit()
            sign_width = self.signLab.frame.size.width
            sign_height = 22
        }
        
        self.signLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(inputTF.snp.bottom).offset(10)
            make.width.equalTo(sign_width + 20)
            make.height.greaterThanOrEqualTo(sign_height)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.top.equalTo(0)
            make.width.equalTo(40)
            make.height.equalTo(40)
        }
        
    }
    
    // shows popup alert animated.
    open func show(){
        self.refreashSnapKitLayout()
        self.frame.size = CGSize.init(width: kScreenWidth, height: kScreenHeight)
        UIApplication.shared.keyWindow?.addSubview(self)
        self.startAnimation()
    }
    
    //开始动画
    /**
     usingSpringWithDamping:(CGFloat)//震动效果，范围0~1，数值越小震动效果越明显
     initialSpringVelocity:(CGFloat)//初始速度，数值越大初始速度越快
     */
    func startAnimation(){
        self.bkgBtnView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
        self.contentView.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
        UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 5) {
            self.bkgBtnView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.7)
            self.contentView.transform = CGAffineTransform.init(scaleX: 1, y: 1)
        }
    }
    
    ///按钮事件
    @objc func bottomBtnAction(){
        if self.alertType == .inputAlert {
            if (self.inputTF.text ?? "").removeAllSapce == "" {
                self.inputWarnLab.text = MMLocalizedString("user_please_input_coupon_code", comment: "请输入优惠码")
                self.updateConstraints()
                return
            }
        }
        self.exchangeCouponByCode(code: self.inputTF.text ?? "")
    }
    
    ///关闭
    @objc func dismissAlertView(){
        self.bkgBtnView.alpha = 1
        UIView.animate(withDuration: 0.24, animations: {
            self.bkgBtnView.alpha = 0
        }) { (flag) in
            self.removeFromSuperview()
        }
    }
    
    open class func showAlertView(title:String? = nil,
                                  message:String? = nil,
                                  detail: String? = nil,
                                  signText: String? = nil,
                                  cancelButtonTitle:String? = nil,
                                  otherButtonTitlesArr:[String]? = nil,
                                  type: CouponAlertViewType? = nil,
                                  clickButtonBlock: CouponAlertViewClickBlock? = nil){
        let alertView = CouponAlertView.init(title: title ?? "", message: message, detail: detail, signText: signText, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: otherButtonTitlesArr)
        alertView.alertType = type ?? .normalAlert
        alertView.clickButtonBlock = clickButtonBlock
        alertView.show()
    }

    
    ///优惠码兑换  1注册页面 2我的优惠券 3商品与服务
    private func exchangeCouponByCode(code: String){
        self.inputTF.resignFirstResponder()
        self.loadingBtn.showLoading()
        self.inputTF.isUserInteractionEnabled = false
        var param: [String: String] = [:]
        param["code"] = code
        param["redemptionLocation"] = "2"
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.couponCodeCodeExchange(param: param), objectType: CodeExchangeResModel.self) { data in
            self.inputTF.isUserInteractionEnabled = true
            self.loadingBtn.handleLoadding()
            let resultObj = data as! CodeExchangeResModel
            if resultObj.code == "1" {
                self.clickButtonBlock?(0, code)
                self.dismissAlertView()
            }else{
                self.inputWarnLab.text = resultObj.msg ?? ""
            }
            self.updateConstraints()
        } error: { err in
            self.inputTF.isUserInteractionEnabled = true
            self.loadingBtn.handleLoadding()
            self.inputWarnLab.text = err?.domain ?? ""
            self.updateConstraints()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

extension CouponAlertView: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "\n" {
            textField.resignFirstResponder()
        }
        return true
    }
}
